<template>
  <div class="currency-exchange-container">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <div class="back-button" @click="goBack">
        <Icon name="arrow-left" size="20" />
      </div>
      <h1 class="page-title">币种兑换</h1>
    </div>
    
    <!-- 兑换表单 -->
    <div class="exchange-form-card">
    <!-- 源币种 - HDFS -->
      <div class="form-group">
        <label class="form-label">从</label>
        <div class="currency-selector hdfs-selector">
          <div class="currency-info">
            <div class="currency-icon hdfs-icon">
              <span>H</span>
            </div>
            <span class="currency-name">HDFS</span>
          </div>
          <div class="balance-info">余额: {{ userBalances || 0 }}</div>
        </div>
      </div>
      
      <!-- 兑换方向指示器 -->
      <div class="exchange-direction">
        <div class="direction-arrow">
          <Icon name="arrow-down" size="20" class="arrow-icon" />
        </div>
      </div>
      
      <!-- 目标币种 -->
      <div class="form-group">
        <label class="form-label">到</label>
        <div class="currency-selector target-selector" @click="showToPopup = true">
          <div class="currency-info">
            <div class="currency-icon" :style="{ backgroundColor: getCurrencyColor(toCurrency) }">
              <span>{{ getFirstChar(toCurrency) }}</span>
            </div>
            <span class="currency-name">{{ toCurrency }}</span>
          </div>
          <Icon name="arrow-down" class="selector-arrow" />
        </div>
      </div>
      
      <!-- 兑换金额 -->
      <div class="form-group">
        <div class="amount-header">
          <label class="form-label">兑换金额</label>
          <span class="use-max" @click="useMaxBalance">全部兑换</span>
        </div>
        <div class="amount-input">
          <input
            type="text"
            v-model="amount"
            placeholder="请输入HDFS兑换金额"
            @input="validateAmount"
          />
          <span class="currency-unit">HDFS</span>
        </div>
      </div>
      
      <!-- 兑换结果 -->
      <div class="form-group result-group">
        <div class="rate-info">
          <div class="rate-value">
            <span class="rate-label">昨日汇率:</span>
            <span class="rate-number">1 HDFS = {{ getCurrentRate() }} {{ toCurrency }}</span>
          </div>
        </div>
      </div>
      
      <!-- 兑换按钮 -->
      <Button type="primary" block class="exchange-button" @click="submitExchange" :disabled="!canExchange">
        立即兑换
      </Button>
      
      <!-- 兑换说明 -->
      <div class="exchange-notes">
        <p>* 兑换将在24小时内完成，完成后将通过系统消息通知您</p>
        <p>* 兑换过程中可能会收取少量手续费</p>
      </div>
    </div>
    
    <!-- 兑换记录 -->
    <div class="exchange-history-card">
      <h2 class="section-title">兑换记录</h2>
      
      <!-- 记录列表 -->
      <div class="history-list">
        <div v-for="record in exchangeRecords" :key="record.id" class="history-item">
          <div class="history-header">
            <span class="history-date">{{ record.createdAt }}</span>
            <Tag :type="record.payStatus === '1' ? 'success' : 'warning'" class="status-tag">
              {{ getStatusText(record.payStatus) }}
            </Tag>
          </div>
          <div class="exchange-details">
            <div class="currency-detail">
              <div class="amount-info">
                <div class="amount">{{ formatNumber(record.fromAmount) }}</div>
                <div class="currency-code">{{ record.from }}</div>
              </div>
            </div>
            <Icon name="arrow" class="exchange-arrow" />
            <div class="currency-detail">
              <div class="currency-icon">
                <span>{{ getFirstChar(record.to) }}</span>
              </div>
              <div class="amount-info">
                <div class="amount">{{ record.toAmount || parseFloat(record.toAmount <= 0) ? '--' : formatNumber(record.toAmount)}}</div>
                <div class="currency-code">{{ record.to }}</div>
              </div>
            </div>
          </div>
          <!-- <div v-if="record.payStatus === '0'" class="estimated-time">
            预计完成时间: {{ record.estimatedCompletion }}
          </div> -->
        </div>
      </div>
      
      <!-- 查看更多 -->
      <div class="view-more" @click="loadMoreRecords">
        查看更多记录
      </div>
    </div>
    
    
    <!-- 目标币种选择弹出层 -->
    <Popup
      v-model:show="showToPopup"
      position="bottom"
      round
      :style="{ maxHeight: '70%' }"
    >
      <div class="currency-popup">
        <div class="popup-header">
          <span class="popup-title">选择目标币种</span>
          <Icon name="cross" @click="showToPopup = false" class="close-icon" />
        </div>
        <div class="currency-list">
          <div
            v-for="currency in targetCurrencies"
            :key="currency"
            class="currency-option"
            @click="selectToCurrency(currency)"
            :class="{ 'selected': currency === toCurrency }"
          >
            <div class="currency-icon" :style="{ backgroundColor: getCurrencyColor(currency) }">
              <span>{{ getFirstChar(currency) }}</span>
            </div>
            <div class="currency-option-content">
              <span class="currency-name">{{ currency }}</span>
              <span class="currency-rate">昨日汇率：1 HDFS = {{ getRate(currency) }} {{ currency }}</span>
            </div>
            <Icon name="success" v-if="currency === toCurrency" class="selected-icon" />
          </div>
        </div>
      </div>
    </Popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showLoadingToast, Icon, Tag, Button, Popup } from 'vant';
import { getExchangeRecords, submitExchange as submitExchangeApi } from '@/api/exchange';
import { getExchangeCurrencies } from '@/api/circulation'
import { getUserWallet } from '@/api/user'
import { formatNumber } from '@/utils/utils'

const router = useRouter();
const route = useRoute();

// 状态变量
const fromCurrency = ref('HDFS'); // 固定为HDFS
const toCurrency = ref('USDT');
const amount = ref('');
const showToPopup = ref(false);
const updateTime = ref('');
const isLoading = ref(false);
const page = ref(1);
const hasMore = ref(true);

// 币种选项 - 排除HDFS
const currencies = ref([]);
const targetCurrencies = computed(() => {
  return currencies.value.filter(c => c !== 'HDFS');
});

// 是否可以兑换
const canExchange = computed(() => {
  return amount.value && Number(amount.value) > 0 && 
         Number(amount.value) <= Number(userBalances.value || 0);
});

const getStatusText = (status) => {
  const statusMap = {
    '0': '待结算',
    '1': '已结算',
    '2': '已拒绝'
  }
  return statusMap[status] || status
}

// 汇率数据
const exchangeRates = ref({});

// 用户余额
const userBalances = ref({});

// 兑换记录
const exchangeRecords = ref([]);

// 获取字符串的第一个字符，处理可能的非字符串类型
const getFirstChar = (str) => {
  if (!str) return '';
  
  // 确保是字符串类型
  const strValue = String(str);
  return strValue.charAt(0);
};

// 初始化数据
const initData = async () => {
  isLoading.value = true;
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  });
  
  try {
    // 获取币种列表
    const currenciesRes = await getExchangeCurrencies();
    if (currenciesRes.code === 0 && currenciesRes.data) {
      // 确保币种是字符串类型
      currencies.value = currenciesRes.data.map(item => {
        // 如果是对象，则获取其name或id属性，否则直接使用
        return typeof item === 'object' ? (item.name || item.id || 'USDT') : String(item);
      });
      
      // 获取汇率信息  
      let rates = {}
      currenciesRes.data.forEach(item => {
        rates[item.icon] = item.rate;
      });
      exchangeRates.value = rates;

      // 如果没有获取到币种，添加默认币种
      if (currencies.value.length === 0) {
        currencies.value = ['USDT', 'BTC', 'ETH', 'DOGE'];
      }
      
      // 确保HDFS在列表中
      if (!currencies.value.includes('HDFS')) {
        currencies.value.push('HDFS');
      }
    } else {
      // 设置默认币种
      currencies.value = ['HDFS', 'USDT', 'BTC', 'ETH', 'DOGE'];
    }
    

    
    // 获取用户余额
    const balanceRes = await getUserWallet({icon: 'HDFS'});
    if (balanceRes.code === 0 && balanceRes.data && balanceRes.data.length > 0) {
      userBalances.value = formatNumber(balanceRes.data[0].balance);
    }
    
    // 获取兑换记录
    await loadExchangeRecords();
    
    // 如果URL中有指定币种，则设置为目标币种
    if (route.query.currency) {
      const targetCurrency = route.query.currency.toString();
      if (currencies.value.includes(targetCurrency) && targetCurrency !== fromCurrency.value) {
        toCurrency.value = targetCurrency;
      }
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
    showToast('数据加载失败，请稍后重试');
  } finally {
    isLoading.value = false;
    showLoadingToast().close();
  }
};

// 加载兑换记录
const loadExchangeRecords = async () => {
  try {
    const recordsRes = await getExchangeRecords({page: page.value,size:10});
    if (recordsRes.code === 0 && recordsRes.data) {
      if (page.value === 1) {
        exchangeRecords.value = recordsRes.data.list;
      } else {
        exchangeRecords.value = [...exchangeRecords.value, ...recordsRes.data.list];
      }
      
      // 判断是否还有更多记录
      hasMore.value = exchangeRecords.value.length < recordsRes.data.total;
    }
  } catch (error) {
    console.error('加载兑换记录失败:', error);
    showToast('加载记录失败，请稍后重试');
  }
};

// 获取当前汇率
const getCurrentRate = () => {
  const key = `${toCurrency.value}`;
  return exchangeRates.value[key] || 0;
};

// 计算兑换结果
const calculateResult = () => {
  const rate = getCurrentRate();
  if (!amount.value || isNaN(Number(amount.value))) return '0';
  return (Number(amount.value) * rate).toFixed(6);
};

// 使用全部余额
const useMaxBalance = () => {
  amount.value = userBalances.value || '0';
};

// 验证输入金额
const validateAmount = (e) => {
  // 只允许数字和一个小数点
  amount.value = e.target.value.replace(/[^0-9.]/g, '');
  
  // 确保只有一个小数点
  const parts = amount.value.split('.');
  if (parts.length > 2) {
    amount.value = parts[0] + '.' + parts.slice(1).join('');
  }
  
  // 限制小数位数为6位
  if (parts.length === 2 && parts[1].length > 6) {
    amount.value = parts[0] + '.' + parts[1].substring(0, 6);
  }
};


// 获取币种颜色
const getCurrencyColor = (currency) => {
  const colorMap = {
    'HDFS': '#3b82f6', // 蓝色
    'USDT': '#26A17B', // 绿色
    'BTC': '#F7931A',  // 橙色
    'ETH': '#627EEA',  // 紫色
    'DOGE': '#C2A633', // 金色
    'USDC': '#2775CA', // 蓝色
    'XRP': '#23292F'   // 深灰色
  };
  
  return colorMap[currency] || '#6B7280'; // 默认灰色
};

// 获取特定币种对的汇率
const getRate = (to) => {
  const rate = exchangeRates.value[to] || 0;
  return formatNumber(parseFloat(rate).toFixed(8));
};

// 选择目标币种
const selectToCurrency = (currency) => {
  toCurrency.value = currency;
  showToPopup.value = false;
};

// 提交兑换
const submitExchange = async () => {
  if (!amount.value || Number(amount.value) <= 0) {
    showToast('请输入有效的兑换金额',1000);
    return;
  }
  
  // 检查余额是否足够
  const balance = Number(userBalances.value || 0);
  if (Number(amount.value) > balance) {
    showToast(`HDFS余额不足`,1000);
    return;
  }
  
  try {
    const result = await submitExchangeApi({
      toIcon: toCurrency.value,
      from: amount.value
    });
    
    if (result.code === 0) {

      // 添加新的兑换记录到列表顶部
      const newRecord = {
        id: Date.now(),
        createdAt: new Date().toISOString().split('T')[0],
        from: fromCurrency.value,
        to: toCurrency.value,
        fromAmount: amount.value,
        toAmount: "0",
        payStatus: '0',
      };
      
      exchangeRecords.value = [newRecord, ...exchangeRecords.value];
      
      // 更新余额
      const newBalance = (Number(userBalances.value) - Number(amount.value)).toString();
      userBalances.value = newBalance;
      
      // 清空输入
      amount.value = '';
    } 
  } catch (error) {
    console.error('提交兑换请求失败:', error);
  } 
};

// 加载更多记录
const loadMoreRecords = () => {
  if (!hasMore.value || isLoading.value) return;
  
  page.value += 1;
  loadExchangeRecords();
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
});

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.currency-exchange-container {
  padding-bottom: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部导航 */
.nav-header {
  display: flex;
  align-items: center;
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.back-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 8px;
}

/* 兑换表单卡片 */
.exchange-form-card {
  margin: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  font-size: 15px;
  color: #333;
  font-weight: 600;
  margin-bottom: 10px;
}

/* 币种选择器 */
.currency-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 16px;
  background-color: #f9f9f9;
}

.hdfs-selector {
  background-color: #edf5ff;
  border-color: #c2d8ff;
  cursor: default;
}

.target-selector {
  cursor: pointer;
  transition: all 0.2s;
}

.target-selector:hover {
  border-color: #3b82f6;
  background-color: #f0f7ff;
}

.currency-info {
  display: flex;
  align-items: center;
}

.currency-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 16px;
}

.hdfs-icon {
  background-color: #3b82f6;
}

.currency-icon span {
  font-weight: bold;
  color: white;
}

.currency-name {
  font-weight: 600;
  font-size: 16px;
}

.balance-info {
  color: #666;
  font-size: 14px;
}

.selector-arrow {
  color: #666;
}

/* 兑换方向 */
.exchange-direction {
  display: flex;
  justify-content: center;
  margin: 16px 0;
}

.direction-arrow {
  width: 40px;
  height: 40px;
  background-color: #f0f7ff;
  border: 1px solid #d9e8ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow-icon {
  color: #3b82f6;
}

/* 金额输入 */
.amount-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.use-max {
  font-size: 14px;
  color: #3b82f6;
  font-weight: 600;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #edf5ff;
  transition: all 0.2s;
}

.use-max:hover {
  background-color: #d9e8ff;
}

.amount-input {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 16px;
  background-color: #fff;
}

.amount-input input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 18px;
  font-weight: 500;
}

.currency-unit {
  color: #666;
  margin-left: 8px;
  font-weight: 500;
}

/* 兑换结果 */
.result-group {
  margin-top: 32px;
}

.result-display {
  display: flex;
  align-items: center;
  border: 1px solid #d9e8ff;
  border-radius: 12px;
  padding: 16px;
  background-color: #f0f7ff;
}

.result-amount {
  flex: 1;
  font-weight: 600;
  font-size: 18px;
  color: #3b82f6;
}

.rate-info {
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

.rate-value {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.rate-label {
  margin-right: 6px;
}

.rate-number {
  font-weight: 500;
  color: #333;
}

.update-time {
  font-size: 12px;
  color: #999;
}

/* 兑换按钮 */
.exchange-button {
  height: 48px !important;
  border-radius: 12px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  margin-top: 16px;
  background-color: #3b82f6 !important;
  border-color: #3b82f6 !important;
}

.exchange-button:disabled {
  opacity: 0.6;
  background-color: #94a3b8 !important;
  border-color: #94a3b8 !important;
}

/* 兑换说明 */
.exchange-notes {
  margin-top: 20px;
  font-size: 13px;
  color: #666;
  line-height: 1.6;
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 8px;
  border-left: 3px solid #3b82f6;
}

/* 兑换记录卡片 */
.exchange-history-card {
  margin: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

/* 记录列表 */
.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 16px;
  transition: all 0.2s;
}

.history-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.history-date {
  font-size: 14px;
  color: #666;
}

.status-tag {
  font-size: 12px !important;
  padding: 2px 10px !important;
  border-radius: 12px !important;
}

.exchange-details {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.currency-detail {
  display: flex;
  align-items: center;
}

.amount-info {
  margin-left: 10px;
}

.amount {
  font-weight: 600;
  font-size: 16px;
}

.currency-code {
  font-size: 13px;
  color: #666;
  margin-top: 2px;
}

.exchange-arrow {
  color: #94a3b8;
  margin: 0 16px;
}

.estimated-time {
  margin-top: 12px;
  font-size: 13px;
  color: #666;
  padding-top: 12px;
  border-top: 1px dashed #eee;
}

/* 查看更多 */
.view-more {
  text-align: center;
  color: #3b82f6;
  font-weight: 500;
  font-size: 15px;
  padding: 14px 0;
  margin-top: 12px;
  cursor: pointer;
  border-top: 1px solid #f0f0f0;
  transition: all 0.2s;
}

.view-more:hover {
  background-color: #f0f7ff;
}

/* 币种选择弹出层 */
.currency-popup {
  padding: 20px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}

.close-icon {
  padding: 8px;
}

.currency-list {
  margin-top: 20px;
}

.currency-option {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.currency-option:hover {
  background-color: #f0f7ff;
}

.currency-option.selected {
  background-color: #edf5ff;
  border: 1px solid #c2d8ff;
}

.currency-option-content {
  display: flex;
  flex-direction: column;
  margin-left: 12px;
}

.currency-rate {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.selected-icon {
  position: absolute;
  right: 16px;
  color: #3b82f6;
}
</style>